package cz.cvut.vrtisja2.muchktom.view.list;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import cz.cvut.vrtisja2.muchktom.Consts;
import cz.cvut.vrtisja2.muchktom.R;
import cz.cvut.vrtisja2.muchktom.data.ItemCrate;
import cz.cvut.vrtisja2.muchktom.view.newItem.NewItemActivity;

public class ListAct extends ListActivity {

	private EditText itemInput;
	private String[] vehicles;
	private ListView list;

	private List<ItemCrate> items;

	private ItemAdapter adapter;
	private ImageButton addItemImgButton;
	private OnClickListener addItemListener;

	public static final String[] CARS = new String[] {
			"Alfa Romeo",
			"Alpina",
			 };
//			"Ariel", "Ascari", "Aston Martin", "Audi", "Bentley", "BMW",
//			"Bristol", "Brooke", "Cadillac", "Callaway", "Campagna",
//			"Caterham", "Chevrolet", "Chrysler", "Citroen", "Corvette",
//			"Daihatsu", "Dodge", "Elfin", "Ferrari", "Fiat", "Ford", "Gumpert",
//			"Holden", "Honda", "Hummer", "Hyundai", "Invicta", "Isuzu",
//			"Jaguar", "Jeep", "Kia", "Koenigsegg", "Lamborghini", "Land Rover",
//			"Lexus", "Lobini", "Lotus", "Marcos", "Maserati", "Maybach",
//			"Mazda", "MB Roadcars", "Mercedes-Benz", "Mini", "Mitsubishi",
//			"Morgan", "NICE", "Nissan", "Noble", "Opel", "Pagani", "Perodua",
//			"Peugeot", "Porsche", "Proton", "Radical", "Renault",
//			"Rolls-Royce", "Saab", "Saturn", "Seat", "Shelby", "Skoda",
//			"Smart", "Spyker", "Ssangyong", "SSC", "Subaru", "Superformance",
//			"Tata", "Tesla", "Toyota", "TVR", "Unique", "Vauxhall",
//			"Volkswagen", "Volvo", "Westfield" };
	//private static final String ItemCrate = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_items);
		this.initListData();
		this.init();

		adapter = new ItemAdapter(this, R.layout.list_item, items);
		this.setListAdapter(adapter);
		 registerForContextMenu(list);
		 
	}

	private void initListData() {
		// Zatim plnim jen falesnymi daty
		int id = 0;
		items = new ArrayList<ItemCrate>();
		for (String s : CARS) {
			ItemCrate item = new ItemCrate();
			item.itemName = s;
			item.itemId = id;
			item.qty = 1;
			item.categoryName = "default";
			item.qtyUnit = "pcs";
			items.add(item);

		}

	}

	private void init() {
		addItemImgButton = (ImageButton) findViewById(R.id.addItemImgButton);
		itemInput = (EditText) findViewById(R.id.newItemInput);
		list=(ListView)  findViewById(android.R.id.list);

		// -----------------------------Listeners-------------------------------------

		addItemListener = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent myIntent = new Intent(ListAct.this,
						NewItemActivity.class);
				// Quick item add
				String itemName;
				int itemQty = 1;
				String inputText = itemInput.getText().toString();
				if (inputText != null) {
					int delimPosition = inputText.indexOf('*');
					try {
						itemQty = Integer.parseInt(inputText
								.substring(delimPosition + 1));
						itemName = inputText.substring(0, delimPosition - 1);
						itemInput.setText("");
						addItemToList(itemName, itemQty, "pcs", "default");
					}
					// Pokud se neco pokazi tak jdu do activyty pro pridani
					// noveho predmetu
					catch (Exception ex) {
						itemName = inputText;
						myIntent.putExtra(Consts.ITEM_NAME, itemName);
						ListAct.this.startActivity(myIntent);
					}

				}

			}
		};
		addItemImgButton.setOnClickListener(addItemListener);

	}
	
	//Plneni kontextoveho menu
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	    ContextMenuInfo menuInfo) {
	  if (v.getId()==android.R.id.list) {
	    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
	    menu.setHeaderTitle(items.get(info.position).itemName);
	    String[] menuItems = new String[] {"edit","delete"};
	    for (int i = 0; i<menuItems.length; i++) {
	      menu.add(Menu.NONE, i, i, menuItems[i]);
	    }
	  }
	}
	
	//Reakce na klik  predmetu v seznamu
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Object o = this.getListAdapter().getItem(position);
		String keyword = o.toString();
		ViewHolder holder;
		TextView textView = (TextView) v.findViewById(R.id.itemName);
		ItemCrate tmpItem = items.get(position);
		holder = (ViewHolder) v.getTag();
		if (tmpItem.marked) {
			tmpItem.marked = false;

			//
			// System.out
			// .println("holder unchecked: " + holder.textView.getText());
			textView.setBackgroundDrawable(null);
		} else {
			tmpItem.marked = true;
			moveItemDown(position);
			textView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.bg_strikethrough));
			
		}
		// // textView.setPaintFlags(textView.getPaintFlags() |
		// // Paint.STRIKE_THRU_TEXT_FLAG);
		// // if(textView.getBackground()==null){
		// //
		// textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_strikethrough));
		// // }
		// // else{
		// // textView.setBackgroundDrawable(null);}

		Log.i("klik", "kliknuto");
		// Toast.makeText(this, "You selected: " + keyword+
		// " on position: "+position, Toast.LENGTH_LONG).show();
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	  AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	  int menuItemIndex = item.getItemId();
	 
	  if(menuItemIndex==Consts.CTX_MENU_DELETE){
		  deleteItemOnposition(info.position);
	  }
	  else if(menuItemIndex==Consts.CTX_MENU_EDIT){
		  openItemDetailInEditMode(info.position);
		  
	  }
	  return true;
	}
	
	// zavola editacni okno pro zvoleny predmet a preda mu potrebne attributy //TODO: musi se vyresit jak si mezi sebou vymeni id kategorii a id qty jednotek
	private void openItemDetailInEditMode(int position) {
		ItemCrate editedItem = items.get(position);
		Intent myIntent = new Intent(ListAct.this,
				NewItemActivity.class);
		
		myIntent.putExtra(Consts.ITEM_NAME, editedItem.itemName);
		myIntent.putExtra(Consts.ITEM_QTY, editedItem.qty);
		myIntent.putExtra(Consts.ITEM_CATEGORY, editedItem.categoryName);
		myIntent.putExtra(Consts.ITEM_QTY_UNIT, editedItem.qtyUnit);
		
		ListAct.this.startActivity(myIntent);
		
	}

	private void deleteItemOnposition(int position) {
		this.items.remove(position);
		adapter.notifyDataSetChanged();		
	}

	private void moveItemDown(int position) {
		ItemCrate tempItem = this.items.get(position);
		tempItem.marked = true;
		this.items.remove(position);
		this.items.add(tempItem);
		adapter.notifyDataSetChanged();
	}

	public void addItemToList(String name, int qty, String qtyUnit,
			String category) {
		ItemCrate item = new ItemCrate();
		item.itemName = name;
		item.qty = qty;
		item.qtyUnit = qtyUnit;
		item.categoryName = category;
		this.items.add(item);
		adapter.notifyDataSetChanged();

	}

	// ******************************Inner classes*******************************
	private class ItemAdapter extends ArrayAdapter<ItemCrate> {

		private final Context mContext;
		private final int mResourceId;

		public ItemAdapter(Context context, int resource,
				List<ItemCrate> objects) {
			super(context, resource, objects);
			mContext = context;
			mResourceId = resource;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			ItemCrate currentItem = ListAct.this.items.get(position);
			
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.list_item_row, null, true);
				holder = new ViewHolder();
				holder.line1 = (TextView) convertView
						.findViewById(R.id.itemName);
				// holder.imageView = (ImageView) convertView
				// .findViewById(R.id.vehicle_image);
				
				holder.line1.setBackgroundDrawable(null);
				holder.line2 = (TextView) convertView
						.findViewById(R.id.itemInfo);
				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}			
			if (currentItem.marked) {
				
				holder.line1.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.bg_strikethrough));
			} else {
			
				holder.line1.setBackgroundDrawable(null);
			}
			// TODO : toto je divne, nemel by si to ten holder pamatovat?
			holder.line1.setText(currentItem.itemName);
			holder.line2.setText(currentItem.qty + " " + currentItem.qtyUnit);

			
			return convertView;
		}

	}

	private class ViewHolder {
		// public ImageView imageView;
		public TextView line1;
		public TextView line2;
		
	}

}
